package com.gpframework.module.controller.process;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.process.domain.GpProcessScheduling;
import com.gpframework.module.process.domain.req.GpProcessSchedulingAdd;
import com.gpframework.module.process.domain.req.GpProcessSchedulingReq;
import com.gpframework.module.process.domain.req.GpProcessSchedulingUpdate;
import com.gpframework.module.process.domain.vo.GpProcessSchedulingVo;
import com.gpframework.module.process.service.IGpProcessSchedulingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
/**
 * @ClassName GpProcessSchedulingController
 * @Author gpframework
 * @Date 2023-12-20
 * @Version 1.0.0
 * @Description 排单Controller
 */
@Validated
@Api(tags = "排单")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/process/scheduling" )
public class GpProcessSchedulingController extends BaseController {

    private final IGpProcessSchedulingService iGpProcessSchedulingService;

 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2023-12-20
  * @Param gpProcessScheduling
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('process:scheduling:list')")
    @GetMapping("/list")
    public TableDataInfo<GpProcessSchedulingVo> list(GpProcessSchedulingReq gpProcessSchedulingReq)
    {
        startPage();
        QueryWrapper<GpProcessScheduling> lqw = new QueryWrapper<GpProcessScheduling>();
        gpProcessSchedulingReq.generatorQuery(lqw,true);
        List<GpProcessSchedulingVo> list = iGpProcessSchedulingService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('process:scheduling:add')" )
    @Log(title = "添加排单" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GpProcessSchedulingAdd gpProcessSchedulingAdd) {
        GpProcessScheduling gpProcessScheduling = Convert.convert(new TypeReference<GpProcessScheduling>() {}, gpProcessSchedulingAdd);
        gpProcessScheduling.setSn(getSn());
        return toAjax(iGpProcessSchedulingService.save(gpProcessScheduling) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('process:scheduling:edit')" )
    @Log(title = "修改排单" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody List<GpProcessSchedulingUpdate> gpProcessSchedulingUpdates) {
        return toAjax(iGpProcessSchedulingService.edit(gpProcessSchedulingUpdates) ? 1 : 0);
    }



    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('process:scheduling:export')" )
    @Log(title = "导出排单" , businessType = BusinessType.EXPORT)
    @ApiOperation("导出加工排单")
    @GetMapping("/export" )
    public AjaxResult export(GpProcessSchedulingReq gpProcessSchedulingReq) {
        QueryWrapper<GpProcessScheduling> lqw = new QueryWrapper<GpProcessScheduling>();
        gpProcessSchedulingReq.generatorQuery(lqw,true);
        List<GpProcessSchedulingVo> list = iGpProcessSchedulingService.listVo(lqw);
        ExcelUtil<GpProcessSchedulingVo> util = new ExcelUtil<GpProcessSchedulingVo>(GpProcessSchedulingVo. class);
        return util.exportExcel(list, "scheduling" );
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('process:scheduling:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GpProcessSchedulingVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProcessSchedulingService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('process:scheduling:remove')" )
    @Log(title = "删除排单" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGpProcessSchedulingService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * @Description 生成收货单
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return AjaxResult
     */
    @ApiOperation("生成收货单")
    @PreAuthorize("@ss.hasPermi('manufacture:createReceiver:add')" )
    @Log(title = "生成收货单" , businessType = BusinessType.INSERT)
    @PostMapping("/createReceiver")
    public AjaxResult createReceiver(@Valid @RequestBody GpProcessSchedulingUpdate gpProcessSchedulingUpdate) {
        if (gpProcessSchedulingUpdate == null || CollectionUtils.isEmpty(gpProcessSchedulingUpdate.getIds())) {
            return AjaxResult.parameterError();
        }
        return toAjax(iGpProcessSchedulingService.createReceiveGoods(gpProcessSchedulingUpdate.getIds(), gpProcessSchedulingUpdate.getCreateBy()) ? 1 : 0);
    }
    /**
     * @Description 确认下单
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return AjaxResult
     */
    @ApiOperation("确认下单")
    @PreAuthorize("@ss.hasPermi('manufacture:createReceiver:add')" )
    @Log(title = "确认下单" , businessType = BusinessType.INSERT)
    @PostMapping("/confirmOrder")
    public AjaxResult confirmOrder(@Valid @RequestBody List<GpProcessSchedulingUpdate> gpProcessSchedulingUpdates) {
        return toAjax(iGpProcessSchedulingService.confirmOrder( gpProcessSchedulingUpdates) ? 1 : 0);
    }
    /**
     * @Description 确认下单
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return AjaxResult
     */
    @ApiOperation("申请退回底布")
    @PreAuthorize("@ss.hasPermi('manufacture:createReceiver:add')" )
    @Log(title = "申请退回底布" , businessType = BusinessType.INSERT)
    @PostMapping("/applyReturnBottomCloth")
    public AjaxResult applyReturnBottomCloth(@Valid @RequestBody GpProcessSchedulingUpdate gpProcessSchedulingUpdate) {
        return toAjax(iGpProcessSchedulingService.applyReturnBottomCloth( gpProcessSchedulingUpdate) ? 1 : 0);
    }
    /**
     * @Description 复制
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("复制")
    @PreAuthorize("@ss.hasPermi('process:scheduling:add')" )
    @Log(title = "复制" , businessType = BusinessType.INSERT)
    @PostMapping("/copy")
    public AjaxResult copy(@Valid @RequestBody GpProcessSchedulingUpdate gpProcessSchedulingUpdate) {
        if (gpProcessSchedulingUpdate == null || gpProcessSchedulingUpdate.getId() == null || gpProcessSchedulingUpdate.getCopyNum() == null) {
            return AjaxResult.parameterError();
        }
        if (gpProcessSchedulingUpdate.getCopyNum() < 1) {
            return AjaxResult.error("复制条数不能小于1");
        }
        return toAjax(iGpProcessSchedulingService.copy(gpProcessSchedulingUpdate.getId(), gpProcessSchedulingUpdate.getCopyNum()) ? 1 : 0);
    }


    /**
     * @Description 拆分订单
     * @Author gpframework
     * @Date 2023-12-20
     * @Param gpProcessScheduling
     * @Return TableDataInfo
     */
    @ApiOperation("拆分订单")
    @PreAuthorize("@ss.hasPermi('process:splitOrders:add')" )
    @Log(title = "拆分订单" , businessType = BusinessType.INSERT)
    @PostMapping("/splitOrders")
    public AjaxResult splitOrders(@Valid @RequestBody GpProcessSchedulingUpdate gpProcessSchedulingUpdate) {
        if (gpProcessSchedulingUpdate == null || gpProcessSchedulingUpdate.getId() == null || gpProcessSchedulingUpdate.getSplitNum() == null) {
            return AjaxResult.parameterError();
        }
        if (gpProcessSchedulingUpdate.getSplitNum() < 1) {
            return AjaxResult.error("拆分条数不能小于1");
        }
        return toAjax(iGpProcessSchedulingService.splitOrders(gpProcessSchedulingUpdate.getId(), gpProcessSchedulingUpdate.getSplitNum()) ? 1 : 0);
    }


    /**
     * 获取生成加工订单号
     */
    private String getSn() {
        String sn = "";

        String yyMMdd = DateUtils.getDate("yyMMdd");
        sn += yyMMdd;

        GpProcessScheduling processScheduling = iGpProcessSchedulingService.getOne(new LambdaQueryWrapper<GpProcessScheduling>()
                .eq(GpProcessScheduling::getDelStatus, YesNoEnum.NO.getKey())
                .isNotNull(GpProcessScheduling::getSn)
                .gt(GpProcessScheduling::getCreateTime, DateUtils.getDate("yyyy-MM-dd 00:00:00"))
                .orderByDesc(GpProcessScheduling::getCreateTime)
                .last("limit 1"));
        if (processScheduling == null) {
            sn += "-1";
        } else {
            String substring = processScheduling.getSn().substring(processScheduling.getSn().lastIndexOf("-") + 1);
            int index = Integer.parseInt(substring) + 1;
            sn += "-" + index;
        }
        return sn;
    }

}
